package com.jiuwan.gamepass.auth.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @version 1.0
 * 功能目的描述 ：  用于   验证码接口   暂时还未使用     ========>>>>>>>>>>>
 * @author： pang-yun
 * @date： 2021-07-01 13:21
 */
@Slf4j
@RestController
public class CaptchaController {

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    //验证码               确定输出格式
    @GetMapping(value = "/captcha",produces = "image/jpeg")
    public void captcha(HttpServletRequest request, HttpServletResponse response) {
        //首先定义response输出类型为image/jpeg格式
        response.setDateHeader("Expires", 0);
        //set standard  http/1.1 no cache headers
        response.setHeader("Cache-Control", "no-store,no-cache,must-revalidate");
        //set ie extended Http/1.1 no cache headers(use addHeader)
        response.addHeader("Cache-Control", "post-check=0,pre-check=0");
        //set stardand http/1.0 no cache headers
        response.setHeader("Pragma", "no-cache");
        //return a jpeg
        response.setContentType("image/jpeg");


        //-------------------------生成验证码------------------
        //获取验证码文本内容
        String text = defaultKaptcha.createText();
        log.info("验证码： "+text);
        //将验证码文本放入session中
        request.getSession().setAttribute("captcha",text);
        //根据文本创建图形验证码
        BufferedImage image = defaultKaptcha.createImage(text);
        ServletOutputStream outputStream=null;
        try{
             outputStream = response.getOutputStream();
             //输出流输出图片，格式为jpg
            ImageIO.write(image,"jpg",outputStream);
            outputStream.flush();
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (null!= outputStream){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


        //-------------------------end-------------------------
    }
}